// (c) Yongjin Park, 2013

#include "expression.hh"
#include "gaussian.hh"
#include "lda.hh"
#include <boost/lexical_cast.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <string>


////////////////////////////////////////////////////////////////
struct prog_args_t
{
  explicit prog_args_t() :
      g_file(""), x_file(""), K(2), // required args
      output("output"), repeat(1), tol(1e-2), max_iter(100), sample(100) // options
  {
  }

  std::string g_file;
  std::string x_file;
  size_t K;
  std::string output;
  size_t repeat;
  double tol;
  size_t max_iter;
  size_t sample;
};

void print_help(const char* prog, const prog_args_t& args)
{
  std::cerr << prog << " -g G.txt -x X.txt -k K -o out" << std::endl;
  std::cerr << "         -i iter -r repeat -t tol -s sample" << std::endl;
  std::cerr << std::endl;
  std::cerr
      << " G.txt  geneset / group file (each line contains row-indexes of X,Y)"
      << std::endl;
  std::cerr << " X.txt  a data matrix (n x p tab-sep real mat)" << std::endl;
  std::cerr << " K      number of topics (default: " << args.K << ")"
      << std::endl;
  std::cerr << " out    output files' header (default: " << args.output << ")"
      << std::endl;
  std::cerr << " iter   max number of iterations (default: " << args.max_iter
      << ")" << std::endl;
  std::cerr << " tol    convergence condition (default: " << args.tol << ")"
      << std::endl;
  std::cerr << " sample number of samples (default: " << args.sample << ")"
      << std::endl;
  std::cerr << " repeat number of repeated fits (default: " << args.repeat
      << ")" << std::endl;
  std::cerr << std::endl;
}

template<typename T>
T get_param(const char* arg, std::string emsg)
{
  T val;
  try
  {
    val = boost::lexical_cast<T>(arg);
  } catch (boost::bad_lexical_cast&)
  {
    err_msg(emsg);
    exit(1);
  }
  return val;
}

bool parse_args(const int argc, const char* argv[], prog_args_t& args_out)
{
  for (int j = 1; j < argc; ++j)
  {
    std::string curr = argv[j];

    if (curr == "-g" && ++j < argc)
    {
      args_out.g_file = argv[j];
    }
    else if (curr == "-x" && ++j < argc)
    {
      args_out.x_file = argv[j];
    }
    else if (curr == "-o" && ++j < argc)
    {
      args_out.output = argv[j];
    }
    else if (curr == "-i" && ++j < argc)
    {
      args_out.max_iter = get_param<size_t>(argv[j], "parsing iter");
    }
    else if (curr == "-s" && ++j < argc)
    {
      args_out.sample = get_param<size_t>(argv[j], "parsing #samples");
    }
    else if (curr == "-k" && ++j < argc)
    {
      args_out.K = get_param<size_t>(argv[j], "parsing K");
    }
    else if (curr == "-r" && ++j < argc)
    {
      args_out.repeat = get_param<size_t>(argv[j], "parsing repeat");
    }
    else if (curr == "-t" && ++j < argc)
    {
      args_out.tol = get_param<double>(argv[j], "parsing tol");
    }
  }

  if (args_out.tol <= 0)
    return false;
  if (args_out.g_file.size() == 0 || args_out.x_file.size() == 0)
    return false;
  if (args_out.K < 2)
    return false;
  return true;
}

typedef expr_vector_t data_type;
typedef multi_gaussian_t func_type;

// void random_seeding_lasso(std::vector<boost::shared_ptr<data_type> >& data_vec,
//     boost::ptr_vector<expr_ptr_set_t<data_type> >& data_sets,
//     boost::ptr_vector<func_type>& topics, const size_t K)
// {
//   random_seeding<data_type, func_type>(data_vec, data_sets, topics, K);
// #ifdef DEBUG
//   TLOG("done random seeding")
// #endif
// }

template<>
void
output_topics(std::string& output, boost::ptr_vector<func_type>& topics)
{
  std::ofstream ofs((output + ".mean").c_str());
  for(size_t i=0; i<topics.size(); ++i)
  {
    topics[i].write_mean(ofs);
    ofs << std::endl;
  }
  ofs.close();
}

void write(std::vector<boost::shared_ptr<data_type> >& data_vec,
    boost::ptr_vector<geneset_t<data_type> >& genesets,
	   boost::ptr_vector<func_type>& topics, std::string output)
{
  output_topics<func_type>(output, topics);
  output_argmax<data_type, func_type>(output, data_vec, topics);
  output_genesets<data_type>(output, genesets);

  std::ofstream hyper((output + ".hyper").c_str(), std::ios::out);
  for (size_t j = 0; j < topics.size(); ++j)
  {
    topics[j].write_hyper(hyper);
    hyper << std::endl;
  }
  hyper.close();
}

////////////////////////////////////////////////////////////////
template<>
double empirical_bayes(boost::ptr_vector<func_type>& func_vec,
		       double rate )
{
  const double n = func_vec.size();
  // a0, b0
  // empirical Bayes of a0 and b0
  // just a simple moment matching
  double a = 1., b;
  {
    // r_i = expected precision
    // a0/b0   = 1/n * sum_i lmd_i
    double mean_r = 0.;
    for (int i = 0; i < func_vec.size(); ++i)
      mean_r += func_vec[i].precision();

    mean_r /= n;
    b = 1. / mean_r;
  }

  double diff = 0.;
  for(size_t k=0; k<func_vec.size(); ++k)
    diff += func_vec[k].update_ab0(a,b) + func_vec[k].optimze_scale();

  diff /= n;

  return diff;
}

////////////////////////////////////////////////////////////////
int main(const int argc, const char* argv[])
{
  prog_args_t args;
  if (!parse_args(argc, argv, args))
  {
    print_help(argv[0], args);
    return -1;
  }

  std::vector<boost::shared_ptr<data_type> > data_vec;
  size_t n, p;
  const char* x_file = args.x_file.c_str();

  if (!read_expr_vec(x_file, data_vec, n, p))
    return -1;

  // read geneset data
  std::string& g = args.g_file;
  boost::ptr_vector<geneset_t<data_type> > genesets;
  double a0 = 1. / ((double) args.K);
  const size_t K = args.K;

  if (!read_genesets(g.c_str(), data_vec, a0, K, genesets))
    return -1;

  fit_lda<data_type, func_type>(data_vec, genesets, p, args);

  return 0;
}
